package com.apiit.webserviceclient.activities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import com.apiit.webserviceclient.R;
import com.apiit.webserviceclient.R.layout;
import com.apiit.webserviceclient.R.menu;
import com.apiit.webserviceclient.utility.BPEL_Process;
import com.apiit.webserviceclient.utility.BPEL_Request;
import com.apiit.webserviceclient.utility.BPEL_Response;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class OPACsearch extends Activity implements OnClickListener {
	// implements OnCheckedChangeListener,
	// OnClickListener

	EditText searchFor;
	EditText type;
	EditText category;
	Spinner Inspinner;
	Spinner Typespinner;
	Spinner Catspinner;
	Spinner Locspinner ;
	Button search;
	String InState = null;
	String TypeState = null;
	String CatState = null;
	String LocState = null;
	ArrayAdapter<CharSequence> Inadapter ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_opacsearch);
		final Intent i = new Intent(this, OPACSearchResult.class);
		searchFor = (EditText) findViewById(R.id.editsearchfor);
		search = (Button) findViewById(R.id.btnSearchnow);

		Inspinner = (Spinner) findViewById(R.id.Inspinner);
		Inspinner.setOnItemSelectedListener(new InStateOnItemSelectedListener());

        Typespinner = (Spinner) findViewById(R.id.Typespinner);
		Typespinner.setOnItemSelectedListener(new TypeStateOnItemSelectedListener());

		
		Catspinner = (Spinner) findViewById(R.id.Categoryspinner);
		Catspinner.setOnItemSelectedListener(new CatInStateOnItemSelectedListener());

		Locspinner = (Spinner) findViewById(R.id.Locationspinner);
		Locspinner.setOnItemSelectedListener(new LocStateOnItemSelectedListener());

		search.setOnClickListener(this);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.opacsearch, menu);
		return true;
	}
	

	public class InStateOnItemSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View itemSelected,
				int pos, long id) {
			
			InState = Inspinner.getItemAtPosition(pos).toString();
			Log.d("charini", InState);
		}

		public void onNothingSelected(AdapterView<?> parent) { // Do nothing
																// here
		}
	}
	

	public class TypeStateOnItemSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View itemSelected,
				int pos, long id) {

			TypeState = Typespinner.getItemAtPosition(pos).toString();
			Log.d("charini", TypeState);

		}

		public void onNothingSelected(AdapterView<?> parent) { // Do nothing
																// here
		}
	}
	

	public class CatInStateOnItemSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View itemSelected,
				int pos, long id) {
			

			CatState = Catspinner.getItemAtPosition(pos).toString();
			Log.d("charini", CatState);

		}

		public void onNothingSelected(AdapterView<?> parent) { // Do nothing
																// here
		}
	}
	

	public class LocStateOnItemSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View itemSelected,
				int pos, long id) {
			
			LocState = Locspinner.getItemAtPosition(pos).toString();
			Log.d("charini", LocState);
		}

		public void onNothingSelected(AdapterView<?> parent) { // Do nothing
																// here
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

		
		BPEL_Process bpelProcess = new BPEL_Process();
		BPEL_Request request = new BPEL_Request();
		request.setUrl("http://webspace1.apiit.lk/gims/library/LibrarySearchMain.asp");
		Map<String, String> xpathMap = new HashMap<String, String>();
		xpathMap.put("message","/html[1]/body[1]/table[2]---");
		//xpathMap.put("output","/html[1]/body[1]/table[1]/tr[1]/th[1]---");
		request.setXpathMap(xpathMap);
		//SearchCriteria=Algorithms&SearchField=ALL&SearchType=Book&SearchCategory=ALGORITHMS&location=CC&action=ProcessLibrarySearch&submit=Search+Now
		//SearchCriteria=Algorithms&SearchField=ALL&SearchType=Book&SearchCategory=ALGORITHMS&location=All&action=ProcessLibrarySearch&submit=Search+Now
		Map<String, String> parametersMap = new HashMap<String, String>();
		parametersMap.put("SearchCriteria", "Algorithms");
		parametersMap.put("SearchField",InState );
		parametersMap.put("SearchType", TypeState);
		parametersMap.put("SearchCategory", CatState);
		parametersMap.put("location", "CC");
		parametersMap.put("action", "ProcessLibrarySearch");
		parametersMap.put("submit", "Search+Now");
		request.setParametersMap(parametersMap);
		
		request.setType("POST");
		BPEL_Response respones = null;
		try {
			respones = bpelProcess.doRequest(request); 
			//String output = respones.getResultsMap().get("output");
			if(respones.getStatus().equalsIgnoreCase("Error")){
				
				AlertDialog.Builder alt = new
						AlertDialog.Builder(this);
				alt.setTitle("Error...");
				alt.setMessage("Error..!! Please try again");
				alt.setNeutralButton("Close", null);
				alt.show();
				
				Intent i = new Intent(this, OPACSearchError.class);
				startActivity(i);
			}
			
			String value = respones.getResultsMap().get("message");
			value = value.trim().replaceAll("&nbsp;", "").replaceAll("Title Code:", "").replaceAll("Call No: ISBN:", "").replaceAll("Author:", "").replaceAll("Type:", "").replaceAll("Category:", "").replaceAll("</form>", "");
			String[] a = value.split("\n");
			
			String [] temparr;
			String tempStringWithSplitter = "";
			BufferedReader br = new BufferedReader(new StringReader(value));
			
			String line;
			try {
				line = br.readLine();
				while (line != null) {
					line = line.trim();
					if(!line.equalsIgnoreCase(""))
					{
						tempStringWithSplitter =tempStringWithSplitter +"====" + line;
					}
					line = br.readLine();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				AlertDialog.Builder alt = new
						AlertDialog.Builder(this);
				alt.setTitle("Error...");
				alt.setMessage("Error..!! Please try again");
				alt.setNeutralButton("Close", null);
				alt.show();
				
				Intent i = new Intent(this, OPACSearchError.class);
				startActivity(i);
			}

		temparr = tempStringWithSplitter.split("====");
			
			Intent i = new Intent(this, OPACSearchResult.class);
			i.putExtra("message", temparr);
			startActivity(i);
			
			Toast.makeText(
					getApplicationContext(),
					"Status: " + respones.getStatus() + " title: "
							+ respones.getResultsMap().get("title")
							+ " name: "
							+ respones.getResultsMap().get("message"),
					Toast.LENGTH_LONG).show();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			AlertDialog.Builder alt = new
					AlertDialog.Builder(this);
			alt.setTitle("Error...");
			alt.setMessage("Error..!! Please try again");
			alt.setNeutralButton("Close", null);
			alt.show();
			
			Intent i = new Intent(this, OPACSearchError.class);
			startActivity(i);
		}

	}

}
